﻿using System.Text;
using FTBS.Models.BLO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FTBS.Models.Entities;
using FTBS.Models.Entities.Concert;
using PagedList;

namespace FTBS.Controllers
{
    public class CustomerController : Controller
    {
        private UserBLO _userBlo = new UserBLO();
        private LevelBLO _levelBlo = new LevelBLO();
        private TicketCartBLO _ticketCartBlo = new TicketCartBLO();
        private TicketDetailsConcertEntityBLO _ticketDetailsConcertEntityBlo = new TicketDetailsConcertEntityBLO();

        /// <summary>
        /// display all customers
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, bool? isSortDescending)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            List<User> listUser = new List<User>();
            listUser = _userBlo.DisplayAllCustomers();

            ViewBag.NameSortParm = "name_desc";
            ViewBag.CurrentSort = sortOrder;

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;
            ViewBag.IsSortDes = false;

            if (!String.IsNullOrEmpty(searchString))
            {

                listUser = listUser.Where(customer => customer.UserName.ToUpper().Contains(searchString.ToUpper())
                                  || customer.FullName.ToUpper().Contains(searchString.ToUpper())
                                  || customer.Email.ToUpper().Contains(searchString.ToUpper())
                                  || customer.Point.ToString().ToUpper().Contains(searchString.ToUpper())).ToList();
            }

            switch (sortOrder)
            {
                case "name_desc":
                    if (isSortDescending == true)
                    {
                        listUser = listUser.OrderByDescending(customer => customer.UserName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listUser = listUser.OrderBy(customer => customer.UserName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "fullname_desc":
                    if (isSortDescending == true)
                    {
                        listUser = listUser.OrderByDescending(customer => customer.FullName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listUser = listUser.OrderBy(customer => customer.FullName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "email_desc":
                    if (isSortDescending == true)
                    {
                        listUser = listUser.OrderByDescending(customer => customer.Email).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listUser = listUser.OrderBy(customer => customer.Email).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "point_desc":
                    if (isSortDescending == true)
                    {
                        listUser = listUser.OrderByDescending(customer => customer.Point).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listUser = listUser.OrderBy(customer => customer.Point).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "status_desc":
                    if (isSortDescending == true)
                    {
                        listUser = listUser.OrderByDescending(customer => customer.IsActive).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listUser = listUser.OrderBy(customer => customer.IsActive).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                default:
                    listUser = listUser.OrderBy(customer => customer.UserName).ToList();
                    ViewBag.IsSortDes = false;
                    break;
            }

            int pageSize = 5;
            int pageNumber = (page ?? 1);

            return View(listUser.ToPagedList(pageNumber, pageSize));
        }

        /// <summary>
        /// active customer
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Active(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBlo.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            bool isActive = _userBlo.ActiveUser(user);
            return RedirectToAction("Index");
        }

        /// <summary>
        /// deactive customer
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Deactive(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBlo.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            bool isActive = _userBlo.DeactiveUser(user);
            return RedirectToAction("Index");
        }
        /// <summary>
        /// Delete user
        /// </summary>
        /// <param name="id"></param>
        /// <returns>Redirect to Index page</returns>
        [HttpDelete, ActionName("Delete")]
        public ActionResult Delete(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBlo.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            _userBlo.DeleteUser(user);
            return RedirectToAction("Index");
        }

        public ActionResult Register()
        {
            ViewBag.UserName = null;
            ViewBag.Email = null;

            List<string> listStrGender = new List<string>();
            listStrGender.Add("Nam");
            listStrGender.Add("Nữ");
            ViewBag.Gender = new SelectList(listStrGender);
            ViewBag.Registing = "Registing";
            return View();
        }

        /// <summary>
        /// create staff
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        [HttpPost]
        public ActionResult Register(User user)
        {
            if (_userBlo.CheckUsername(user))
            {
                ViewBag.UserName = user.UserName;
            }
            if (_userBlo.CheckEmail(user))
            {
                ViewBag.Email = user.Email;
            }
            if (ModelState.IsValid)
            {
                if (!_userBlo.CheckUsername(user) && !_userBlo.CheckEmail(user))
                {
                    ViewBag.UserName = null;
                    ViewBag.Email = null;
                    user.Password = _userBlo.GenerateMD5(user.Password);
                    if (_userBlo.Register(user))
                    {
                        this.Session["RoleName"] = "Customer";
                        this.Session["Account"] = user.FullName;
                        this.Session["UserName"] = user.UserName;
                        string title = "Đăng ký tài khoản thành công!!!";
                        string Str = "<html>";
                        Str += "<head>";
                        Str += "<title>";
                        Str += "</title>";
                        Str += "</head>";
                        Str += "<body>";
                        Str += "<h2>Thông tin tài khoản bạn đã đăng ký</h2>";
                        Str += "<table border=1 max-width=50% cellpadding=2px cellspacing=2px>";
                        Str += "<tr>";
                        Str += "<td>Tên tài khoản</td>";
                        Str += "<td>" + user.UserName + "</td>";
                        Str += "</tr>";
                        Str += "<tr>";
                        Str += "<td>Họ tên</td>";
                        Str += "<td>" + user.FullName + "</td>";
                        Str += "</tr>";
                        Str += "<tr>";
                        Str += "<td>Giới tính</td>";
                        Str += "<td>" + user.Gender + "</td>";
                        Str += "</tr>";
                        Str += "<tr>";
                        Str += "<td>Tuổi</td>";
                        Str += "<td>" + user.Age + "</td>";
                        Str += "</tr>";
                        Str += "<tr>";
                        Str += "<td>Địa chỉ</td>";
                        Str += "<td>" + user.Address + "</td>";
                        Str += "</tr>";
                        Str += "<tr>";
                        Str += "<td>Số điện thoại</td>";
                        Str += "<td>" + user.PhoneNumber + "</td>";
                        Str += "</tr>";
                        Str += "<tr>";
                        Str += "<td>Email</td>";
                        Str += "<td>" + user.Email + "</td>";
                        Str += "</tr>";
                        Str += "</table><br/>";
                        Str +=
                            "Hãy nhấn vào <a href='http://localhost:4236/'>đây</a> để có thể truy cập vào website.";
                        Str += "</body>";
                        Str += "</html>";
                        _userBlo.SendMail(user.Email, user.UserName, title, Str);
                        return RedirectToAction("RegisterSuccessful");
                    }
                }
            }

            List<string> listStrGender = new List<string>();
            listStrGender.Add("Nam");
            listStrGender.Add("Nữ");
            ViewBag.Gender = new SelectList(listStrGender);

            return View(user);
        }

        public void RegisterSuccessful()
        {
            this.Response.Redirect("/Home/Customer");
        }

        public ActionResult ViewCustomerAccount()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return Redirect("/Home/Announcement");
            }
            if (this.Session["UserName"] != null && this.Session["RoleName"].ToString().Trim() == "Customer")
            {
                var customer = _userBlo.LoadUserByUserName(this.Session["UserName"].ToString().Trim());
                if (customer.LevelId != null)
                {
                    ViewBag.Level = _levelBlo.GetLevelById(customer.LevelId).LevelName;
                }
                return View(customer);
            }
            else
            {
                return HttpNotFound();
            }
        }

        public ActionResult EditCustomerAccount()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return Redirect("/Home/Announcement");
            }
            var customer = new User();
            if (this.Session["UserName"] != null && this.Session["RoleName"].ToString().Trim() == "Customer")
            {
                customer = _userBlo.LoadUserByUserName(this.Session["UserName"].ToString().Trim());
            }
            List<String> listStrGender = new List<String>();
            if (customer.Gender == "Nam")
            {
                listStrGender.Add("Nam");
                listStrGender.Add("Nữ");
            }
            else
            {
                listStrGender.Add("Nữ");
                listStrGender.Add("Nam");
            }
            ViewBag.Gender = new SelectList(listStrGender);
            ViewBag.Email = null;
            return View(customer);
        }

        /// <summary>
        /// edit info of staff
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        [HttpPost]
        public ActionResult EditCustomerAccount(User user)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return Redirect("/Home/Announcement");
            }
            var email = _userBlo.LoadUserByUserName(this.Session["UserName"].ToString().Trim()).Email;
            if (email == user.Email)
            {
                ViewBag.Email = null;
            }
            if (email != user.Email)
            {
                ViewBag.Email = user.Email;
            }
            if (ModelState.IsValid)
            {
                var isExist = _userBlo.CheckEmail(user);
                if (!isExist || (ViewBag.Email == null))
                {
                    if (!isExist && ViewBag.Email != null)
                    {
                        string title = "Xác nhận thay đổi email!!!";
                        var safePass = _userBlo.RandomString(6);
                        string str = "<html>";
                        str += "<head>";
                        str += "<title>";
                        str += "</title>";
                        str += "</head>";
                        str += "<body>";
                        str += "Chào bạn,";
                        str += "<br />";
                        str += "Chúng tôi xin gửi bạn MÃ AN TOÀN để xác nhận việc thay đổi email cho tài khoản ";
                        str += user.UserName;
                        str += " là ";
                        str += safePass;
                        str += "<br />";
                        str +=
                            "Hãy nhấn vào <a href='http://localhost:4236/'>đây</a> để có thể truy cập vào website. Nên thay đổi mật khẩu để đảm bảo an toàn cho tài khoản của bạn!!!";
                        str += "</body>";
                        str += "</html>";
                        _userBlo.SendMail(email, user.UserName, title, str);
                        this.Session["SafePass"] = safePass;
                        return View("ConfirmChangeEmail", user);
                    }
                    else if (_userBlo.EditCustomer(user))
                    {
                        this.Session["Account"] = user.FullName;
                        return RedirectToAction("ViewCustomerAccount");
                    }
                }
            }
            List<String> listStrGender = new List<String>();
            if (user.Gender == "Nam")
            {
                listStrGender.Add("Nam");
                listStrGender.Add("Nữ");
            }
            else
            {
                listStrGender.Add("Nữ");
                listStrGender.Add("Nam");
            }
            ViewBag.Gender = new SelectList(listStrGender);
            return View(user);
        }

        public ActionResult ChangePassword()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return Redirect("/Home/Announcement");
            }
            return View();
        }

        public String SubmitChangePassword(string oldPass, string newPass)
        {
            if (this.Session["UserName"] != null)
            {
                String oPass = _userBlo.GenerateMD5(oldPass);
                String password = _userBlo.LoadUserByUserName(this.Session["UserName"].ToString().Trim()).Password;
                if (oPass == password)
                {
                    String nPass = _userBlo.GenerateMD5(newPass);
                    if (_userBlo.ChangePassword(this.Session["UserName"].ToString().Trim(), nPass))
                    {
                        return "changeSuccessful";
                    }
                    return "Fail";
                }
                return "Fail";
            }
            return "Fail";
        }

        public ActionResult ViewPastBooking(int? page)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return Redirect("/Home/Announcement");
            }
            if (this.Session["UserName"] != null)
            {
                List<TicketCart> listTicketCarts = new List<TicketCart>();
                listTicketCarts = _ticketCartBlo.GetAllTicketCartByUser(this.Session["UserName"].ToString().Trim());
                int pageSize = 10;
                int pageNumber = (page ?? 1);

                return View(listTicketCarts.ToPagedList(pageNumber, pageSize));
            }
            else
            {
                return Redirect("/Home/Announcement");
            }
        }

        public ActionResult ViewTicketCartDetails(string id, int? page)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return Redirect("/Home/Announcement");
            }
            if (this.Session["UserName"] != null)
            {
                List<TicketDetailsConcertEntity> listTicketsOfTicketCartDetails = new List<TicketDetailsConcertEntity>();
                listTicketsOfTicketCartDetails = _ticketDetailsConcertEntityBlo.LoadTicketsByCartId(id);
                int pageSize = 10;
                int pageNumber = (page ?? 1);

                return View(listTicketsOfTicketCartDetails.ToPagedList(pageNumber, pageSize));
            }
            else
            {
                return Redirect("/Home/Announcement");
            }
        }

        public ActionResult ForgetPassword()
        {
            return View();
        }

        /// <summary>
        /// check username and email in database and send password if they exist
        /// </summary>
        /// <param name="username"></param>
        /// <param name="email"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        public String CheckAndSendEmail(string username, string email)
        {
            string title = "Quên mật khẩu!!!";
            User user = _userBlo.LoadUserByUserName(username);
            if (user != null)
            {
                if (email == user.Email)
                {
                    var newPassword = _userBlo.RandomString(8);
                    if (_userBlo.ChangePassword(username, _userBlo.GenerateMD5(newPassword)))
                    {
                        string Str = "<html>";
                        Str += "<head>";
                        Str += "<title>";
                        Str += "</title>";
                        Str += "</head>";
                        Str += "<body>";
                        Str += "<h2>Tài khoản và mật khẩu hiện tại của bạn là:</h2>";
                        Str += "<table border=1 max-width=50% cellpadding=2px cellspacing=2px>";
                        Str += "<tr>";
                        Str += "<td>Tên tài khoản</td>";
                        Str += "<td>" + username + "</td>";
                        Str += "</tr>";
                        Str += "<tr>";
                        Str += "<td>Mật khẩu</td>";
                        Str += "<td>" + newPassword + "</td>";
                        Str += "</tr>";
                        Str += "</table><br/>";
                        Str +=
                            "Hãy nhấn vào <a href='http://localhost:4236/'>đây</a> để có thể truy cập vào website. Nên thay đổi mật khẩu để đảm bảo an toàn cho tài khoản của bạn!!!";
                        Str += "</body>";
                        Str += "</html>";
                        _userBlo.SendMail(email, username, title, Str);
                        return "OK";
                    }
                }
            }
            return "Fail";
        }

        public string EditEmail(string fullName, string gender, int age, string address, string email, string phone)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return "SessionTimeOut";
            }

            User user = _userBlo.LoadUserByUserName(this.Session["UserName"].ToString().Trim());
            user.FullName = fullName;
            user.Gender = gender;
            user.Age = age;
            user.Address = address;
            user.Email = email;
            user.PhoneNumber = phone;
            if (_userBlo.EditCustomer(user))
            {
                this.Session["Account"] = user.FullName;
                return "Successfull";
            }
            return "fail";
        }

        public ActionResult Details(string id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            var customer = _userBlo.LoadUserByUserName(id);
            if (customer.LevelId != null)
            {
                ViewBag.Level = _levelBlo.GetLevelById(customer.LevelId).LevelName;
                return View(customer);
            }
            else
            {
                ViewBag.Level = "Thành Viên";
                return View(customer);
            }

        }

    }
}
